package com.lei.app.provider;

import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/4/9
 * 描述：房间提供着
 */
public class MemoryRoomProvider  implements WsRoomProvider {

    /***
     * 房间与 人员 之间的对应关系
     */
    protected ConcurrentHashMap<String, ConcurrentSkipListSet<String>> rooms = new ConcurrentHashMap<>();

    @Override
    public Set<String> getIdByRoomName(String room) {
        return getRoom(room);
    }

    @Override
    public void join(String room, String wsid) {
        getRoom(room).add(wsid);
    }

    @Override
    public void remove(String room, String wsid) {
        getRoom(room).remove(wsid);
    }

    public Set<String> getRoom(String room) {
        ConcurrentSkipListSet<String> _room = rooms.get(room);
        if (_room == null) {
            _room = new ConcurrentSkipListSet<String>();
            ConcurrentSkipListSet<String> prev = rooms.putIfAbsent(room, _room);
            if (prev != null) {
                _room = prev;
            }
        }
        return _room;
    }

    @Override
    public Iterable<String> getRoomNames() {
        return new ArrayList<>(rooms.keySet());
    }
}